package io.github.harmonly.skyblock.manager;

import io.github.harmonly.skyblock.util.TimeHelper;
import org.bukkit.*;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

public class WorldManager {

    private static final Map<String, UUID> map = new ConcurrentHashMap<>();

    public static void disable() {
        map.values().forEach(WorldManager::unload);
        map.clear();
    }

    public static World load(String name) {
        WorldCreator wc = new WorldCreator(name);
        World world = wc.createWorld();
        if (world == null) {
            return null;
        }
        setup(world);
        map.put(name, world.getUID());
        return world;
    }

    public static void unload(UUID uid) {
        unload(Bukkit.getWorld(uid));
    }

    public static void unload(World world) {
        if (world != null) {
            Bukkit.unloadWorld(world, true);
            map.remove(world.getName());
        }
    }

    public static World getWorld(String name) {
        return Bukkit.getWorld(name);
    }

    public static World getWorld(UUID uid) {
        return Bukkit.getWorld(uid);
    }

    public static void setup(World world) {
        // 设置世界时间
        world.setTime((TimeHelper.getHour() + 18) % 24 * 1000L);
        world.setFullTime(0);
        // 设置世界规则
        world.setDifficulty(Difficulty.HARD);
        world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, true);
        world.setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, false);
        world.setGameRule(GameRule.DO_FIRE_TICK, false);
        world.setGameRule(GameRule.DO_LIMITED_CRAFTING, false);
        world.setGameRule(GameRule.DO_MOB_SPAWNING, false);
        world.setGameRule(GameRule.DO_WEATHER_CYCLE, false);
        world.setGameRule(GameRule.KEEP_INVENTORY, true);
        world.setGameRule(GameRule.MOB_GRIEFING, false);
        world.setGameRule(GameRule.NATURAL_REGENERATION, false);
        world.setGameRule(GameRule.SHOW_DEATH_MESSAGES, false);
        world.setGameRule(GameRule.DISABLE_RAIDS, true);
        world.setGameRule(GameRule.DO_INSOMNIA, false);
        world.setGameRule(GameRule.DO_IMMEDIATE_RESPAWN, true);
        world.setGameRule(GameRule.DO_PATROL_SPAWNING, false);
        world.setGameRule(GameRule.DO_TRADER_SPAWNING, false);
        world.setGameRule(GameRule.DO_WARDEN_SPAWNING, false);
        world.setGameRule(GameRule.RANDOM_TICK_SPEED, 0);
        world.setGameRule(GameRule.SPAWN_RADIUS, 0);
        world.setGameRule(GameRule.MAX_ENTITY_CRAMMING, 10);
    }
}
